#include "MainWidget.h"
#include "ui_MainWidget.h"
#include <QMessageBox>
#include <QCloseEvent>

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);
    this->setWindowTitle("易码");
    this->setWindowIcon(QIcon(":/imagee/logo.png"));

    Init();
    OnConnect();
}

MainWidget::~MainWidget()
{
    if (highlighter_ != nullptr)
    {
       highlighter_->deleteLater();
    }
    delete ui;
}

void MainWidget::closeEvent(QCloseEvent *event)
{
    if (!ui->toolButton_kithara_start->isEnabled())
    {
        QMessageBox::information(this, "Tip", "请先关闭内核");
        event->ignore();
        return;
    }

    QWidget::closeEvent(event);
}

void MainWidget::Init()
{
    // 设置一些基本的语法高亮
    highlighter_ = new LuaSyntaxHighlighter(ui->plainTextEdit->document());

    business_ = new Business(this);
    const QString file_path = QApplication::applicationDirPath() + "/" + LUA_FILE_NAME;
    lua_file_ = new QFile(file_path);

    // 文件存在，读取内容显示信息
    if (lua_file_->exists())
    {
        lua_file_->open(QIODevice::ReadOnly);
        ui->plainTextEdit->setPlainText(lua_file_->readAll());
        lua_file_->close();
    }

    ui->toolButton_kithara_start->setEnabled(true);
    ui->toolButton_kithara_stop->setEnabled(false);
}

void MainWidget::OnConnect()
{
    // 信号与槽连接
    connect(ui->toolButton_kithara_start, &QToolButton::clicked, this, &MainWidget::OnStartButtonClicked);
    connect(ui->toolButton_kithara_stop, &QToolButton::clicked, this, &MainWidget::OnStopButtonClicked);
    connect(ui->toolButton_start, &QToolButton::clicked, this, &MainWidget::OnExecuteScript);
    connect(ui->toolButton_clerar, &QToolButton::clicked, this, &MainWidget::OnClearText);
}

void MainWidget::OnExecuteScript()
{
    if (ui->toolButton_kithara_start->isEnabled())
    {
        QMessageBox::information(this, "Tip", "请先启动内核");
        return;
    }

    if (!business_->RunStatus())
    {
        QMessageBox::information(this, "Tip", "脚本执行中..");
        return;
    }

    // 清空文件
    if (!lua_file_->open(QIODevice::WriteOnly))
    {
        QMessageBox::information(this, "Tip", "保存数据失败");
        return;
    }

    lua_file_->resize(0);
    lua_file_->write(ui->plainTextEdit->toPlainText().toUtf8());
    lua_file_->flush();
    lua_file_->close();

    // 执行脚本
    business_->SetRunScript(true);
}

void MainWidget::OnStartButtonClicked()
{
    if (business_->Start())
    {
        ui->toolButton_kithara_start->setEnabled(false);
        ui->toolButton_kithara_stop->setEnabled(true);
    }
    else
    {
        QMessageBox::information(this, "Tip", "内核启动失败");
    }
}

void MainWidget::OnStopButtonClicked() const
{
    business_->Stop();

    ui->toolButton_kithara_start->setEnabled(true);
    ui->toolButton_kithara_stop->setEnabled(false);
}

void MainWidget::OnClearText() const
{
    ui->plainTextEdit->clear();
}


